$(function(){
	$('input[name="begDt"], input[name="endDt"]').datepicker({
		format: "yyyy-mm-dd",
	    todayBtn: "linked",
	    language: "zh-CN",
	    autoclose: true,
	    todayHighlight: true
	});

	var today = getDay(0);
	var yesterday = getDay(-1);
	$('input[name="begDt"]').val(yesterday);
	$('input[name="endDt"]').val(today);
});

var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);

myApp.controller('ishipmentCtrl', function($scope, $http) {
	//global variable
	$scope.selectedRows = [];
	//init page item
	$scope.init = function() {
		$scope.stList = [{"id":0, "lb":"在用"},{"id":1, "lb":"停用"}];
			httpPost($http, {"url":ctx+"/constractor/findListBy", "data": {"ffMap":{"st":0}}}, function(data){
				$scope.constractorList = data.dt;
			}, function(){
				toastError("初始化承运商列表失败。");
			});
			httpPost($http, {"url":ctx+"/driver/findListBy", "data": {"ffMap":{"st":0}}}, function(data){
				$scope.driverList = data.dt;
			}, function(){
				toastError("初始化司机列表失败。");
			});
			httpPost($http, {"url":ctx+"/vehicleType/findListBy", "data": {"ffMap":{"st":0}}}, function(data){
				$scope.vehicleTypeList = data.dt;
			}, function(){
				toastError("初始化运输工具类型列表失败。");
			});
			httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"shipmentMethod","st":0}}}, function(data){
				$scope.shipment_methodList = data.dt;
			}, function(){
				toastError("初始化运输方式列表失败。");
			});
	};
	$scope.init();
	
	//grid
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		
		columnDefs : [
		{
			field : "id",
			displayName : "ID", visible : false
		},
		{
			field : "orderCd",
			displayName : "订单编号",width:160
		},
		{
			field : "legs_no",
			displayName : "分段订单号",width:160
		},
		{
			field : "statusName",
			displayName : "订单状态",width:160
		},
		{
			field : "stName",
			displayName : "状态",width:160
		},
		{
			field : "platformName",
			displayName : "平台",width:160
		},
		{
			field : "clientName",
			displayName : "客户",width:160
		},
		{
			field : "constractorName",
			displayName : "承运商",width:160
		},
		{
			field : "vehicleName",
			displayName : "运输工具",width:160
		},
		{
			field : "shipment_methodName",
			displayName : "运输方式",width:160
		},
		{
			field : "formCd",
			displayName : "出发地",width:160
		},
		{
			field : "toCd",
			displayName : "目的地",width:160
		},
		{
			field : "formName",
			displayName : "发货方名称",width:160
		},
		{
			field : "formlikeName",
			displayName : "发货方联系人",width:160
		},
		{
			field : "formPhone",
			displayName : "发货方电话",width:160
		},
		{
			field : "formAddr",
			displayName : "发货方地址",width:160
		},
		{
			field : "toName",
			displayName : "收货方名称",width:160
		},
		{
			field : "tolikeName",
			displayName : "收货方联系人",width:160
		},
		{
			field : "toPhone",
			displayName : "收货方电话",width:160
		},
		{
			field : "toAddr",
			displayName : "收货方地址",width:160
		},
		{
			field : "shipmentId",
			displayName : "调度单号",width:160
		},
		{
			field : "shipmentType",
			displayName : "配载方式",width:160
		},
		{
			field : "quantity",
			displayName : "件数",width:160
		},
		{
			field : "weight",
			displayName : "重量",width:160
		},
		{
			field : "volume",
			displayName : "体积",width:160
		},
		{
			field : "palletsum",
			displayName : "托数",width:160
		},
		{
			field : "expense",
			displayName : "一口价",width:160
		},
		{
			field : "bag",
			displayName : "零箱数",width:160
		},
		{
			field : "ordertime",
			displayName : "开单时间",width:160
		},
		{
			field : "billtime",
			displayName : "计费周期",width:160
		},
		{
			field : "planltime",
			displayName : "计划离开时间",width:160
		},
		{
			field : "leavetime",
			displayName : "出发时间",width:160
		},
		{
			field : "arrivetime",
			displayName : "到达时间",width:160
		},
		],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		//enablePinning : true,
		//showColumnMenu : true,
		//showGroupPanel : true,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		plugins : [ /*new ngGridFlexibleHeightPlugin()*/ ],
		i18n: 'zh-cn', rowHeight : 25, footerRowHeight : 35,
		showFooter : true
	};
	
	$scope.query = function() {
		closeModal($("#queryFormModal"));
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			httpPost($http, {"url":ctx + '/legs/findListBy', "data":requestBody, "ifBlock":true}, function(data){
				$scope.dt = data.dt;
				$scope.tt = data.tt;	
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};

	//$scope.query();

	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	
	//crud
	$scope.onOpenQueryFormModal = function() {
		openModal($("#queryFormModal"));
	};
	//创建配载号
	$scope.onOpenEditFormModal = function(type, id) {
		if(type=="add"){
			$scope.editForm = {};
		}else if(type=="upd"){
			//if($scope.selectedRows.length != 1) { toastWarning("请选择一笔记录进行编辑。"); return; }
			httpGet($http, {"url":ctx+'/legs/id/'+id, "ifBlock":true}, function(data){
				$scope.editForm = data.dt;
			}, function(errMsg){
				toastWarning("查询此笔记录失败。");
			});
		}
		openModal($("#editFormModal"));
	};
	
	//登记配车
	$scope.onOpenEditFormModal1 = function(type, id) {
		if(type=="add"){
			$scope.editForm1 = {};
			$("#e").change(function(){
				var id=$scope.editForm1.constractorId;
				httpGet($http, {"url":ctx+'/constractor/id/'+id, "ifBlock":true}, function(data){	
					$scope.editForm1.name=data.dt['name'];
					$scope.editForm1.shipment_method=data.dt['shipment_method'];
					httpPost($http, {"url":ctx+"/vehicle/findListBy", "data": {"ffMap":{"constractorId":id,"st":0}}}, function(data){
						$scope.vehicleList = data.dt;				
					}, function(){
						toastError("初始化运输工具列表失败。");
					});
				});	
			});
			$("#vh").click(function(){
				var vid=$scope.editForm1.vehicleId;
				httpGet($http, {"url":ctx+'/vehicle/id/'+vid, "ifBlock":true}, function(data){
					$scope.editForm1.vehicleNo=data.dt['vehicleNo'];
					$scope.editForm1.vehicleTypeId=data.dt['vehicleTypeId'];
					$scope.editForm1.driverId=data.dt['driverId'];
				}, function(){
					toastError("初始化运输工具列表失败。");
				});
			});
		}else if(type=="upd"){
			//if($scope.selectedRows.length != 1) { toastWarning("请选择一笔记录进行编辑。"); return; }
			httpGet($http, {"url":ctx+'/legs/id/'+id, "ifBlock":true}, function(data){
				$scope.editForm = data.dt;
			}, function(errMsg){
				toastWarning("查询此笔记录失败。");
			});
		}
		openModal($("#editFormModal1"));
	};
	
	
	
	
	$scope.onOpenDelFormModal = function() {
		var selectedRowsLength = $scope.selectedRows.length;
		if(selectedRowsLength < 1) { toastWarning("请至少选择一笔记录进行删除。"); return; }
		dialogConfirm("是否确认删除选择的"+selectedRowsLength+"笔记录？", function(){
			var selectedRowsId = [];
			$.each($scope.selectedRows, function(idx, obj){
				selectedRowsId.push(obj.id);
			});
			httpPost($http, {"url":ctx + '/legs/updStByIds', "params":{"ids":selectedRowsId, "st":1}, "ifBlock":true}, function(data){
				toastSuccess("删除成功");
				$scope.query();
			}, function(errMsg){
				toastError("删除失败。" + errMsg);
			});
		});
	};
	
	$("#c").change(function(){
		$scope.initChange();
	});
	//按市内市外查找
		$scope.initChange=function(){
		//$("#tree").css("display","block");
		//$(".aa").css("display","");
		$("#tree li").not(":first").remove();
		httpPost($http, {"url":ctx + '/tempShipment/findListBy',"data": {"ffMap":{"code":"未配载"}},"ifBlock":true}, function(data){
			$scope.o=data.dt[0];
			var id=data.dt[0]['id'];
			$("#tree li:first-child").attr("id",""+id+"");
			var quantity=data.dt[0]['quantity'];
			var weight=data.dt[0]['weight'];
			var volume=data.dt[0]['volume'];
			var points=data.dt[0]['points'];
			if(quantity==null){
				quantity=0;
			}
			if(weight==null){
				weight=0;
			}
			if(volume==null){
				volume=0;
			}
			if(points==null){
				points=0;
			}
			$("#n").text(points+"/"+quantity+"/"+weight+"/"+volume);
		httpPost($http, {"url":ctx + '/tempShipment/findListBy',"data": {"ffMap":{"code":"配载"}},"ifBlock":true}, function(data){
			$scope.tempshipList=data.dt;
			var ul=$("#tree");
			var squantity=0;
			var spoints=0;
			var sweight=0;
			var svolume=0;
			for(var i=0;i<data.dt.length;i++){
			var id=data.dt[i]['id'];
			var code=data.dt[i]['code'];
			var constractorId=data.dt[i]['constractorId'];
			var li;
			if(constractorId!=null){
				 li="<li id='"+id+"'><img src='/res_oms/theme-b/imgs/e03.gif' style='width:17px;margin-right: 20px;'/><a href='#' style='margin-top: -17px;display: block;margin-left: 20px;font-size: 12px;text-decoration:none;'><span class='"+id+"'></span><img src='/res_oms/theme-b/imgs/e04.gif' style='width:22px;margin-left: 10px;'/></a></li>";
			}else{
				 li="<li id='"+id+"'><img src='/res_oms/theme-b/imgs/e03.gif' style='width:17px;margin-right: 20px;'/><a href='#' style='margin-top: -17px;display: block;margin-left: 20px;font-size: 12px;text-decoration:none;'><span class='"+id+"'></span></a></li>";
			}			
			var quantity=data.dt[i]['quantity'];
			var weight=data.dt[i]['weight'];
			var volume=data.dt[i]['volume'];
			var points=data.dt[i]['points'];			
			squantity+=quantity;
			sweight+=weight;
			svolume+=volume;
			spoints+=points;
			ul.append(li);
			$("."+id+"").text("【"+code+"】"+points+"/"+quantity+"/"+weight+"/"+volume);
			}	
			//赋值
			$("#p span").text(data.dt.length);
			spoints+=$scope.o.points;
			squantity+=$scope.o['quantity'];
			sweight+=$scope.o['weight'];
			svolume+=$scope.o['volume'];
			$("#o span").text(spoints);
			//总件数
			$("#j span").text(squantity);
			//总质量
			$("#w span").text(sweight);
			//总体积
			$("#v span").text(svolume);
			
			//点击选中
			$("#tree li").click(function() {
			
			var $this=$(this);
			var tempshipmentId=$(this).attr("id");
			$(this).css("background","#DBEAF9").siblings().css("background","#ffffff");
			var shipmentId={"tempshipmentId":tempshipmentId};
			//查询
			$scope.onQuery = function(){
				$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
				$scope.pagingOptions.currentPage = 1;
				$scope.queryForm=shipmentId;
				httpGet($http, {"url":ctx+'/tempShipment/id/'+tempshipmentId, "ifBlock":true}, function(data){
					$(".p").text(data.dt['code']);
					$(".j").text(data.dt['quantity']);
					$(".w").text(data.dt['weight']);
					$(".v").text(data.dt['volume']);
				});
			};
			
			//创建配载
			$scope.onSaveEditForm = function(){
				var selectedRowsLength = $scope.selectedRows.length;
				var selectedRowsId = [];
				$.each($scope.selectedRows, function(idx, obj){
					selectedRowsId.push(obj.id);
				});	
				var quantity=0;
				var weight=0;
				var volume=0;
				var points=0;
				for(var i=0;i<selectedRowsLength;i++){
					quantity+=$scope.selectedRows[i]['quantity'];
					weight+=$scope.selectedRows[i]['weight'];
					volume+=$scope.selectedRows[i]['volume'];
					points++;
				}
				$scope.editForm.quantity=quantity;
				$scope.editForm.weight=weight;
				$scope.editForm.volume=volume;
				$scope.editForm.points=points;
				closeModal($("#editFormModal"));
				httpPost($http, {"url":ctx + '/tempShipment/save', "data":$scope.editForm, "ifBlock":true}, function(data){
					var id=data.dt[0];
					toastSuccess("保存成功");
					$scope.query();
					//更新leg的id
					httpPost($http, {"url":ctx + '/legs/updStByIds', "params":{"ids":selectedRowsId,"tempshipmentId":id}, "ifBlock":true}, function(data){
						
					});
					//更新temp的重量
					httpGet($http, {"url":ctx+'/tempShipment/id/'+tempshipmentId, "ifBlock":true}, function(data){					
						var tquantity=data.dt['quantity']-quantity;
						var tweight=data.dt['weight']-weight;
						var tvolume=data.dt['volume']-volume;
						var tpoints=data.dt['points']-points;
						httpPost($http, {"url":ctx + '/tempShipment/updStById', "params":{"id":tempshipmentId,"quantity":tquantity, "points":tpoints,"weight":tweight,"volume":tvolume}, "ifBlock":true}, function(data){
							httpGet($http, {"url":ctx+'/tempShipment/id/'+tempshipmentId, "ifBlock":true}, function(data){
								$(".p").text(data.dt['code']);
								$(".j").text(data.dt['quantity']);
								$(".w").text(data.dt['weight']);
								$(".v").text(data.dt['volume']);
								$scope.initChange();
							});
						});
					}, function(errMsg){
						toastWarning("查询此笔记录失败。");
					});
					
				}, function(errMsg){
					toastError("保存失败。" + errMsg);
				});
			};
			//取消配载
			$scope.cancel=function(){
				//获取值
				httpGet($http, {"url":ctx+'/tempShipment/id/'+tempshipmentId, "ifBlock":true}, function(data){
					$scope.editForm1=data.dt;
					//删除掉该项纪录
					httpPost($http, {"url":ctx+'/tempShipment/delById/',"params":{"id":tempshipmentId}, "ifBlock":true}, function(data){						
						httpPost($http, {"url":ctx + '/tempShipment/findListBy',"data": {"ffMap":{"code":"未配载"}},"ifBlock":true}, function(data){
							var id=data.dt[0]['id'];
							var wquantity=$scope.editForm1['quantity']+data.dt[0]['quantity'];
							var wweight=$scope.editForm1['weight']+data.dt[0]['weight'];
							var wvolume=$scope.editForm1['volume']+data.dt[0]['volume'];
							var wpoints=$scope.editForm1['points']+data.dt[0]['points'];
							httpPost($http, {"url":ctx + '/tempShipment/updStById', "params":{"id":data.dt[0]['id'],"quantity":wquantity, "points":wpoints,"weight":wweight,"volume":wvolume}, "ifBlock":true}, function(data){
								httpPost($http, {"url":ctx + '/legs/updStById', "params":{"id":$scope.editForm1['id'],"tempshipmentId":id}, "ifBlock":true}, function(data){								
									$scope.initChange();
									$(".p").text('');
									$(".j").text(0);
									$(".w").text(0);
									$(".v").text(0);
									$scope.query();
								});
							});
						});							
					});
				});
			};			
				//登记配车
				$scope.onSave=function(){
					closeModal($("#editFormModal1"));
					httpPost($http, {"url":ctx + '/tempShipment/updStByIds', "params":{"ids":$this.attr('id'), "vehicleId":$scope.editForm1.vehicleId,"constractorId":$scope.editForm1.constractorId,"driverId":$scope.editForm1.driverId,"shipment_method":$scope.editForm1.shipment_method}, "ifBlock":true}, function(data){
						$scope.initChange();
					}, function(){
						toastError("更新此笔纪录失败");
					});
				};
				//确认配载
				$scope.confirmp=function(){
					//获取当前选择的tempshipment的值
					httpGet($http, {"url":ctx+'/tempShipment/id/'+$this.attr('id'), "ifBlock":true}, function(data){
						//更新legs
						httpPost($http, {"url":ctx + '/legs/updByTempShipmentId', "params":{"tempShipmentId":$this.attr('id'), "vehicleId":data.dt['vehicleId'],"constractorId":data.dt['constractorId'],"driverId":data.dt['driverId'],"shipment_method":data.dt['shipment_method']}, "ifBlock":true}, function(data){				
						}, function(){
							toastError("更新此笔纪录失败");
						});
					});
					//更新tempshipment表的状态
					httpPost($http, {"url":ctx + '/tempShipment/updStatusById', "params":{"id":$this.attr('id'),"status":"shipmentEd"}, "ifBlock":true}, function(data){					
					},function(){
						toastError("更新失败失败");
					});					
					//生成调度单
				};
			});
		});
		});
	};
});